package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.common.dtos.AdminLoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.admin.AdUser;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements  AdUserService {
    @Autowired
    private AdUserMapper adUserMapper;
    @Override
    public ResponseResult login(AdminLoginDto loginDto) {
         //用户根据用户名和密码登录
        if(loginDto == null || StringUtils.isEmpty(loginDto.getName()) || StringUtils.isEmpty(loginDto.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        //1.查询用户
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, loginDto.getName()));
        if(adUser == null ) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //2.密码需要手动加盐验证
        String loginPwd = loginDto.getPassword();
        String password = DigestUtils.md5DigestAsHex((loginPwd + adUser.getSalt()).getBytes());
        if(password.equals(adUser.getPassword())){
            //3.返回用户的token和用户信息
            Map<String,Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

    }
}
